package com.us.usws.service.ro.impl;

import java.util.ArrayList;
import java.util.List;

import net.iwsh.core.utils.converter.BeanConverter;

import com.us.usws.dao.SysObjDAO;
import com.us.usws.model.domain.system.SysObj;
import com.us.usws.model.flat.system.DOSysObj;
import com.us.usws.service.ro.SysObjROService;

public class SysObjROServiceImpl implements SysObjROService {

	private SysObjDAO dao = new SysObjDAO();
	private BeanConverter bc = BeanConverter.getDefaultConverter();

	@Override
	public DOSysObj getObj(int id) {
		return dao.getObj(id);
	}

	@Override
	public List<DOSysObj> getAllObjs() {
		return dao.getAllObjs();
	}

	@Override
	public SysObj getObjTree(int rootId) {
		List<DOSysObj> allObjs = getAllObjs();
		SysObj ret = null;
		for (DOSysObj each : allObjs) {
			if (each.getId() == rootId) {
				ret = bc.gen(each, SysObj.class);
				break;
			}
		}
		//if null
		if (ret == null) {
			return null;
		}

		//fill children
		ret.setChildren(getChildren(rootId, allObjs));
		return ret;
	}

	/**
	 * get children
	 * @param rootId
	 * @param allObjs
	 * @return
	 */
	private List<SysObj> getChildren(int rootId, List<DOSysObj> allObjs) {
		List<SysObj> ret = new ArrayList<SysObj>();
		for (DOSysObj each : allObjs) {
			if (each.getParentId() == rootId) {
				ret.add(bc.gen(each, SysObj.class));
			}
		}
		if (ret.isEmpty()) {
			return null;
		}
		//fill children
		for (SysObj each : ret) {
			each.setChildren(getChildren(each.getId(), allObjs));
		}
		return ret;
	}

}
